package org.smartboot.sosa.plugin.poi;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;

/**
 * Excel文件解析
 * 
 * @author Seer
 * @version ExcelReader.java, v 0.1 2016年6月17日 上午9:40:28 Seer Exp.
 */
public class ExcelReader {

	/**
	 * 读取文件
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public HSSFWorkbook readExcel(InputStream is) throws IOException {
		return new HSSFWorkbook(is);
	}

	/**
	 * @param excel
	 * @param index
	 * @return
	 */
	public HSSFSheet readSheet(HSSFWorkbook excel, int index) {
		return excel.getSheetAt(index);
	}

	public <T> List<T> readRows(HSSFSheet sheet, int start, int end, RowConverter<T> convert) {
		end = end < sheet.getLastRowNum() ? end : sheet.getLastRowNum();
		if (start < 0 || start > end) {
			return null;
		}
		List<T> list = new ArrayList<T>(end - start + 1);
		for (int rowNum = start; rowNum <= end; rowNum++) {
			HSSFRow hssfRow = sheet.getRow(rowNum);
			if (hssfRow == null || isBlankRow(hssfRow)) {
				continue;
			}
			T t = convert.converter(hssfRow);
			if (t != null) {
				list.add(t);
			}
		}
		return list;
	}

	/**
	 * 是否为空行
	 * 
	 * @return
	 */
	private boolean isBlankRow(HSSFRow row) {
		Iterator<Cell> iterator = row.cellIterator();
		while (iterator.hasNext()) {
			if (StringUtils.isNotBlank(iterator.next().toString())) {
				return false;
			}
		}
		return true;
	}

	public static void main(String[] args) throws IOException {
		InputStream is = new FileInputStream("/Users/seer/Downloads/教师管理.xls");
		ExcelReader reader = new ExcelReader();

		HSSFWorkbook hssfWorkbook = reader.readExcel(is);
		HSSFSheet sheet = reader.readSheet(hssfWorkbook, 0);
		reader.readRows(sheet, 0, sheet.getLastRowNum(), new RowConverter<String>() {
			int i = 0;

			@Override
			public String converter(HSSFRow row) {
				System.out.println(i++);
				return null;
			}
		});
	}
}
